<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\controller\Base;
use service\ApiReturn;

/**
 * 图片上传接口
 * @package app\api\controller\v1
 */
class Upload extends Base
{
    use \app\common\traits\controller\Upload;

    //继承中间件

    /**
     * 上传图片
     * @param $data
     * @param array $user
     * @return \think\response\Json
     * @since 2019/4/20 11:30
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function upload_img($data, $user = [])
    {
        $dir = $data['dir'] ? $data['dir'] : 'images';
        $module = $data['module'] ? $data['module'] : 'user';
        $name = 'file';//表单FILE名称
        if (empty($_FILES['file'])) {
            return ApiReturn::r(lang('未获取上传文件，请检查是否开启相册权限'));
        }
        // 临时取消执行时间限制
        set_time_limit(0);
        try {
            config('upload_image_size', 1024 * 20);//限制大小为2M
            $infos = $this->saveFilesTo($dir, $module, $name);
            $arr = [];
            foreach ($infos as $info) {
                $arr[] = [
                    'id' => $info['id'],
                    'path' => $this->_getFileUrl($info['path']),
                    'thumb' => $this->_getFileUrl($info['thumb'])
                ];
            }
        } catch (\Exception $e) {
            return ApiReturn::r(0, [], $e->getMessage());
        }
        return ApiReturn::r(1, $arr, lang('上传成功'));
    }
}
